package handler

import (
	"github.com/gin-gonic/gin"
	"repo-sys/cache"
	"repo-sys/model"
	"repo-sys/pkg"
	"time"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}

	redis_ksy := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_ksy).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败3次，禁止登录",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_ksy)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_ksy, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "登入失败3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
